package com.zgw.his.emr.resource;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.eclipse.core.runtime.Platform;

import com.zgw.his.emr.model.RootRecord;
import com.zgw.his.emr.parser.XmlDumper;

//记录资源管理
public class RecordResourceManager {
	static final String path = Platform.getInstallLocation().getURL().getPath()
			+ "record_lib/";

	public static final boolean saveRecordToFile(RootRecord record)
			throws IOException {
		String id = record.getIdentifier();
		XmlDumper d = new XmlDumper(record);
		String content = d.dump();

		File fp = new File(path + id + ".xml");
		if (fp.exists()) {
			fp.delete();
		}
		boolean newf = fp.createNewFile();
		if (newf) {
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(fp);
				// OutputFormat format=new OutputFormat();
				// format.setIndentSize(2);
				// format.setNewlines(true);
				// format.setTrimText(true);
				// format.setPadText(true);
				// format.setEncoding("GBK");
				// XMLWriter writer=new XMLWriter(out,format);
				// writer.write(content);
				// writer.close();
				out.write(content.getBytes());
			} finally {
				out.close();
			}
		}
		return newf;
	}

	public static final String findRecordContent(String idf) throws Exception {
		String recordContent = null;
		File file = new File(path + idf + ".xml");
		if (file.exists()) {
			FileInputStream in = new FileInputStream(file);
			try {
				int count = 0;
				byte[] b = new byte[500];
				StringBuffer sb = new StringBuffer();
				while ((count = in.read(b)) > 0) {
					sb.append(new String(b, 0, count));
				}
				recordContent = sb.toString();
			} finally {
				in.close();
			}
		}
		return recordContent;
	}
}
